/*
 * @Descripttion: 工具集
 * @version: 1.2
 * @LastEditors: sakuya
 * @LastEditTime: 2022年5月24日00:28:56
 */

import CryptoJS from 'crypto-js';
import sysConfig from "@/config";

const tool = {}

/* localStorage */
tool.data = {
	set(key, data, datetime = 0) {
		//加密
		if(sysConfig.LS_ENCRYPTION == "AES"){
			data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
		}
        let cacheValue = {
            content: data,
            datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
        }
        return localStorage.setItem(key, JSON.stringify(cacheValue))
	},
	get(key) {
        try {
            const value = JSON.parse(localStorage.getItem(key))
            if (value) {
                let nowTime = new Date().getTime()
                if (nowTime > value.datetime && value.datetime != 0) {
                    localStorage.removeItem(key)
                    return null;
                }
				//解密
				if(sysConfig.LS_ENCRYPTION == "AES"){
					value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
				}
                return value.content
            }
            return null
        } catch (err) {
            return null
        }
	},
	remove(key) {
		return localStorage.removeItem(key)
	},
	clear() {
		return localStorage.clear()
	}
}

/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}

/*cookie*/
tool.cookie = {
	set(name, value, config={}) {
		var cfg = {
			expires: null,
			path: null,
			domain: null,
			secure: false,
			httpOnly: false,
			...config
		}
		var cookieStr = `${name}=${escape(value)}`
		if(cfg.expires){
			var exp = new Date()
			exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)
			cookieStr += `;expires=${exp.toGMTString()}`
		}
		if(cfg.path){
			cookieStr += `;path=${cfg.path}`
		}
		if(cfg.domain){
			cookieStr += `;domain=${cfg.domain}`
		}
		document.cookie = cookieStr
	},
	get(name){
		var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"))
		if(arr != null){
			return unescape(arr[2])
		}else{
			return null
		}
	},
	remove(name){
		var exp = new Date()
		exp.setTime(exp.getTime() - 1)
		document.cookie = `${name}=;expires=${exp.toGMTString()}`
	}
}

/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if(isFull){
		if(document.exitFullscreen) {
			document.exitFullscreen();
		}else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		}else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		}else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	}else{
		if(element.requestFullscreen) {
			element.requestFullscreen();
		}else if(element.msRequestFullscreen) {
			element.msRequestFullscreen();
		}else if(element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		}else if(element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}

/* 复制对象 */
tool.objCopy = function (obj) {
	return JSON.parse(JSON.stringify(obj));
}

/** 数据验证 */
tool.check = {
	// 空字符串  
	isEmpty(str) {  
		if ((str == null) || (str.toString().replace(/\s+/g, "") == "")) {  
			return true;  
		} else {  
			return false;  
		}
	},
	//正整数
	isDigits(str)
	{
		if (tool.check.isEmpty(str))  return true;
        var reg = /^\d+$/;
        return reg.test(str);
	},
	// 小数精确度（maxL：整数部分长度，maxF：小数部分长度）  
	isMaxLengthForDouble(str, maxL=9, maxF =2) 
	{ 
		if (tool.check.isEmpty(str)) {  
			return true;  
		}
		var vals = str.split(".");
		if(vals.length ==1)
		{
			if(vals[0].length > maxL)
			{
				return false; 
			}
		}else if(vals.length ==2){
			if(vals[1].length > maxF)
			{
				return false; 
			}
		}else if(vals.length > 2){
			return false; 
		}
		return true;    
	}  
}

/* 字符串处理 */
tool.str = {
	//str.format("{0}-{1}","你好", "世界")
	format(formatted, args) {
		for (let i = 0; i < args.length; i++) {
			let regexp = new RegExp('\\{' + i + '\\}', 'gi')
			formatted = formatted.replace(regexp, args[i])
		}
		return formatted
	}
}
/** 计算 */
tool.calculation ={
	//加法函数，用来得到精确的加法结果
	add(arg1,arg2)
	{
		var r1 = tool.calculation.deal(arg1);
		var r2 = tool.calculation.deal(arg2);
		var m = Math.pow(10, Math.max(r1, r2))
		return(arg1 * m + arg2 * m) / m
	},
	//乘法函数，用来得到精确的乘法结果
	mul(arg1, arg2) {
		var m = 0;
		m += deal(arg1);
		m += deal(arg2);
		var r1 = Number(arg1.toString().replace(".", ""));
		var r2 = Number(arg2.toString().replace(".", ""));
		return(r1 * r2) / Math.pow(10, m)
	},
	//除法函数，用来得到精确的除法结果
	div(arg1, arg2) {
		var t1 = deal(arg1);
		var t2 = deal(arg2);
		var r1 = Number(arg1.toString().replace(".", ""))
		var r2 = Number(arg2.toString().replace(".", ""))
		return(r1 / r2) * Math.pow(10, t2 - t1);
	},
	//求小数点后的数据长度
	deal(arg) {
		var t = 0;
		try {
			t = arg.toString().split(".")[1].length
		} catch(e) {}
		return t;
	}
}
/* json处理 */
tool.json = {
	/* 取值 */
	get(def, obj) {
		try {
			for (var i = 2; i < arguments.length; i++) obj = obj[arguments[i]];
		} catch (e) { }
		return obj != null ? obj : def;
	},
	/* 赋值 */
	set(obj) {
		let o = obj;
		for (let i = 1; i < arguments.length - 1; i++) {
			if (i == arguments.length - 2) {
				if (arguments[i + 1] != null) o[arguments[i]] = arguments[i + 1];
				else if (o[arguments[i]] != null) delete o[arguments[i]];
			} else {
				if (o[arguments[i]] == null || (typeof o[arguments[i]] != "object")) o[arguments[i]] = {};
				o = o[arguments[i]];
			}
		}
		return obj;
	},
	/* 取值，若为空则填充默认值 */
	fill(def, obj) {
		try {
			for (let i = 2; i < arguments.length; i++) {
				if (obj[arguments[i]] == null) {
					// 当前键没有对应的值，则进行填充
					let value = {};
					if (i == arguments.length - 1) {
						// 是最后一个键，赋默认值
						value = def;
					} else {
						// 不是最后一个键
						if (/^(0|\-?[1-9][0-9]*)$/.test(arguments[i + 1] + "")) {
							// 若为整数，赋数组
							value = []
						}
					}
					if (Array.isArray(obj)) { // 当前对象为，数组
						obj.splice(arguments[i], 1, value)
					} else { // 当前对象为，非数组
						obj[arguments[i]] = value;
					}
				}
				obj = obj[arguments[i]];
			}
		} catch (e) { }
		return obj != null ? obj : def;
	},
	parse(str) {
		try {
			return JSON.parse(str);
		} catch (e) {
			console.log(e)
		}
		return null;
	},
	/**转字符串 */
	tostr(obj) {
		try {
			return JSON.stringify(obj);
		} catch (e) {
		}
		return null;
	},
	/* 复制对象 */
	copy(obj) {
		try {
			return JSON.parse(JSON.stringify(obj));
		} catch (e) {
		}
		return null;
	},
	/* 合并对象 */
	merge() {
		return lodash.merge(...arguments);
	}
}

/* 日期格式化 */
tool.dateFormat = function (date, fmt='yyyy-MM-dd hh:mm:ss') {
	date = new Date(date)
	var o = {
		"M+" : date.getMonth()+1,                 //月份
		"d+" : date.getDate(),                    //日
		"h+" : date.getHours(),                   //小时
		"m+" : date.getMinutes(),                 //分
		"s+" : date.getSeconds(),                 //秒
		"q+" : Math.floor((date.getMonth()+3)/3), //季度
		"S"  : date.getMilliseconds()             //毫秒
	};
	if(/(y+)/.test(fmt)) {
		fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in o) {
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		}
	}
	return fmt;
}

/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if(!num.includes('.')){
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
}

/* 常用加解密 */
tool.crypto = {
	//MD5加密
	MD5(data){
		return CryptoJS.MD5(data).toString()
	},
	//BASE64加解密
	BASE64: {
		encrypt(data){
			return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
		},
		decrypt(cipher){
			return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
		}
	},
	//AES加解密
	AES: {
		encrypt(data, secretKey, config={}){
			if(secretKey.length % 8 != 0){
				console.warn("[SCUI error]: 秘钥长度需为8的倍数，否则解密将会失败。")
			}
			const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return result.toString()
		},
		decrypt(cipher, secretKey, config={}){
			const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return CryptoJS.enc.Utf8.stringify(result);
		}
	}
}


tool.response = function (res) {
	var message = "";
	var content = tool.json.get("", res, "content");
	var errdata = tool.json.get([], res, "data");
	for (let key in errdata) {
		message += '<div>' + errdata[key] + '</div>';
	}
	var title = "提示信息";
	if (message != "") {
		title = content;
	} else {
		message = content;
	}
	return { "title": title, "message": message };
}
export default tool
